package com.chare.mail;

import com.chare.pojo.Employee;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.thymeleaf.context.Context;
import java.util.Date;

@Component
public class MailRe {
    private static final Logger logger = LoggerFactory.getLogger(MailRe.class);
@Autowired private  JavaMailSender javaMailSender;
@Autowired private  MailProperties mailProperties;
    @Autowired private TemplateEngine templateEngine;
    //邮件发送

    @RabbitListener(queues = "mailwoke")
    public  void handler(Employee employee) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper minehelper = new MimeMessageHelper(message, true);

        try {
            //发件人
            minehelper.setFrom(mailProperties.getUsername());
            //收件人
            minehelper.setTo(employee.getEmail());
            //主题
            minehelper.setSubject("入职欢迎邮件");
            //发送日期
            minehelper.setSentDate(new Date());
            //邮件内容
            Context context=new Context();
            context.setVariable("name",employee.getName());
            context.setVariable("posName",employee.getPosition().getName());
            context.setVariable("joblevelName",employee.getJoblevel().getName());
            context.setVariable("departmentName",employee.getDepartment().getName());
            String mail = templateEngine.process("mail",  context);
            minehelper.setText(mail,true);
            //发送邮件
            javaMailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
            logger.error("邮件发送失败=====>{}", e.getMessage());
        }
    }
}
